package com.molyfun.parents.activity.myorder;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.common.BaseActivity;
import com.molyfun.parents.activity.myorder.view.OrderView;
import com.molyfun.parents.fragment.dialog.CommonInputDialogFragment;
import com.molyfun.parents.rest.BaseResponse;
import com.molyfun.parents.rest.RestClient;
import com.molyfun.parents.rest.bean.GetOrderListResponse;
import com.molyfun.parents.rest.bean.OrderDetailResponse;
import com.molyfun.parents.rest.bean.RefundOrderRequest;
import com.molyfun.parents.uievent.EventDispatcherEnum;
import com.molyfun.parents.uievent.UIEventListener;
import com.molyfun.parents.view.ThreeTabBar;
import com.molyfun.parents.view.swipeRefreshLayout.SwipeRefreshLayout;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MineOrderActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, SwipeRefreshLayout.OnLoadListener, ThreeTabBar.ThreeBarClickListener,
        OrderView.OrderViewCallback, UIEventListener, View.OnClickListener {

    public static final int REQUEST_SECOND = 1001;

    @InjectView(R.id.order_top_bar)
    ThreeTabBar mOrderTopBar;
    @InjectView(R.id.order_list)
    RecyclerView mRecyclerView;
    @InjectView(R.id.empty_layout)
    LinearLayout mEmptyLayout;
    @InjectView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @InjectView(R.id.base_title_left)
    ImageView mTitleLeft;
    @InjectView(R.id.base_title)
    TextView mTitle;

    private LinearLayoutManager mLayoutManager;
    private OrderAdapter mOrderAdapter;

    private int mCurrentPage = RestClient.DEFAULT_PAGE;
    private boolean mHasMoreData = true;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REQUEST_SECOND:
                    if (mOrderAdapter != null) {
                        mOrderAdapter.notifyDataSetChanged();
                    }
                    sendEmptyMessageDelayed(REQUEST_SECOND, 1000);
                    break;
            }
        }
    };

    public static void startActivity(Context context){
        Intent intent = new Intent();
        intent.setClass(context, MineOrderActivity.class);
        context.startActivity(intent);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_order);
        ButterKnife.inject(this);
        getSupportActionBar().setTitle("");
        mTitle.setText("我的订单");
        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setOnLoadListener(this);
        mSwipeRefreshLayout.setTopColor(R.color.refresh_color_01, R.color.refresh_color_02,
                R.color.refresh_color_02, R.color.refresh_color_01);
        mSwipeRefreshLayout.setBottomColor(R.color.color_transparent, R.color.color_transparent,
                R.color.color_transparent, R.color.color_transparent);
        mSwipeRefreshLayout.setMode(SwipeRefreshLayout.Mode.BOTH);
        mSwipeRefreshLayout.setLoadNoFull(true);

        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mOrderAdapter = new OrderAdapter(this, this, getSupportFragmentManager());
        mRecyclerView.setAdapter(mOrderAdapter);
        loadData(mOrderTopBar.getCurrentChooseTab(), true);
        mOrderTopBar.setThreeBarClickListener(this);
        mOrderTopBar.initData("全部", "已支付", "未支付");
        MFPApplication.getInstance().getEventController().addUIEventListener(EventDispatcherEnum.UI_EVENT_WECHAT_PAY_SUCCESS, this);
        MFPApplication.getInstance().getEventController().addUIEventListener(EventDispatcherEnum.UI_EVENT_ALIPAY_SUCCESS, this);
        mTitleLeft.setOnClickListener(this);
    }

    @Override
    public void onOrderPay(OrderDetailResponse.OrderBean orderBean) {
        OrderDetailActivity.startActivity(this, orderBean);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.base_title_left:
                finish();
                break;
        }
    }

    @Override
    public void onOrderCancel(String orderId) {
        cancelOrder(orderId);
    }

    @Override
    public void onOrderDel(String orderId) {
        delOrder(orderId);
    }

    @Override
    public void onThreeBarClick(int chooseTab) {
        loadData(chooseTab, true);
    }

    @Override
    public void onRefound(String orderId) {
        refundOrder(orderId);
    }

    @Override
    public void onRefresh() {
        loadData(mOrderTopBar.getCurrentChooseTab(), true);
        mSwipeRefreshLayout.setRefreshing(false);
        mSwipeRefreshLayout.setLoading(false);
    }

    @Override
    public void onLoad() {
        mSwipeRefreshLayout.setRefreshing(false);
        mSwipeRefreshLayout.setLoading(false);
        if (mHasMoreData) {
            mCurrentPage++;
            loadData(mOrderTopBar.getCurrentChooseTab(), false);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mHandler.sendEmptyMessage(REQUEST_SECOND);
    }

    @Override
    public void onPause() {
        super.onPause();
        mHandler.removeMessages(REQUEST_SECOND);
    }

    private void loadData(int currentTab, final boolean isRefresh) {
        switch (currentTab) {
            case ThreeTabBar.ThreeTabChooseTab.BAR_ONE:
                getOrderList("", isRefresh);
                break;
            case ThreeTabBar.ThreeTabChooseTab.BAR_TWO:
                getOrderList("pass", isRefresh);
                break;
            case ThreeTabBar.ThreeTabChooseTab.BAR_THREE:
                getOrderList("init", isRefresh);
                break;
        }
    }

    private void delOrder(String orderId) {
        Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().delOrder(orderId);
        call.enqueue(new Callback<BaseResponse>() {
            @Override
            public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                dismissProgressDialog();
                if (response.body() != null && response.body().getCode() == 200) {
                    toast("删除成功");
                    loadData(mOrderTopBar.getCurrentChooseTab(), true);
                } else {
                    toast("删除失败" + (response.body() == null ? "" : response.body().getMsg()));
                }

            }

            @Override
            public void onFailure(Call<BaseResponse> call, Throwable t) {
                dismissProgressDialog();
            }
        });

    }

    private void refundOrder(final String orderId) {

        new CommonInputDialogFragment.CommonInputDialogBuilder("申请退款", "", "请输入退款原因...")
                .setOnCommonInputCallback(new CommonInputDialogFragment.OnCommonInputCallback() {
                    @Override
                    public void onInputConfirm(String content) {

                        RefundOrderRequest refundOrderRequest = new RefundOrderRequest();
                        refundOrderRequest.setOrderid(orderId);
                        refundOrderRequest.setRefundreason(content);

                        Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().refundOrder(refundOrderRequest);
                        call.enqueue(new Callback<BaseResponse>() {
                            @Override
                            public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                                dismissProgressDialog();
                                if (response.body() != null && response.body().getCode() == 200) {
                                    toast("退款申请成功");
                                    loadData(mOrderTopBar.getCurrentChooseTab(), true);
                                } else {
                                    toast("退款申请失败" + (response.body() == null ? "" : response.body().getMsg()));
                                }

                            }

                            @Override
                            public void onFailure(Call<BaseResponse> call, Throwable t) {
                                dismissProgressDialog();
                            }
                        });

                    }
                })
                .build(getSupportFragmentManager().beginTransaction());


    }

    private void cancelOrder(String orderId) {
        Call<BaseResponse> call = MFPApplication.getInstance().getRestClient().cancelOrder(orderId);
        call.enqueue(new Callback<BaseResponse>() {
            @Override
            public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
                dismissProgressDialog();
                if (response.body() != null && response.body().getCode() == 200) {
                    toast("取消成功");
                    loadData(mOrderTopBar.getCurrentChooseTab(), true);
                } else {
                    toast("取消失败" + (response.body() == null ? "" : response.body().getMsg()));
                }

            }

            @Override
            public void onFailure(Call<BaseResponse> call, Throwable t) {
                dismissProgressDialog();
            }
        });

    }

    private void getOrderList(String status, final boolean isRefresh) {
        if (isRefresh) {
            mCurrentPage = RestClient.DEFAULT_PAGE;
        }

        showProgressDialog();
        Call<GetOrderListResponse> call = MFPApplication.getInstance().getRestClient().getOrderList(status, mCurrentPage, RestClient.DEFAULT_PAGE_SIZE);
        call.enqueue(new Callback<GetOrderListResponse>() {
            @Override
            public void onResponse(Call<GetOrderListResponse> call, Response<GetOrderListResponse> response) {
                dismissProgressDialog();
                if (response.body() != null && response.body().getData() != null && response.body().getData() != null) {
                    if (isRefresh) {
                        if (response.body().getData().size() > 0) {
                            mOrderAdapter.refreshData(response.body().getData());
                            mHasMoreData = true;
                            mEmptyLayout.setVisibility(View.GONE);
                        } else {
                            mHasMoreData = false;
                            mOrderAdapter.clearAll();
                            mEmptyLayout.setVisibility(View.VISIBLE);
                        }
                    } else {
                        if (response.body().getData().size() > 0) {
                            mHasMoreData = true;
                        } else {
                            mHasMoreData = false;
                        }
                        mOrderAdapter.addAll(response.body().getData());
                    }

                }
            }

            @Override
            public void onFailure(Call<GetOrderListResponse> call, Throwable t) {
                mOrderAdapter.clearAll();
                mEmptyLayout.setVisibility(View.VISIBLE);
                dismissProgressDialog();
            }
        });
    }

    @Override
    public void handleUIEvent(Message msg) {
        if (msg.what == EventDispatcherEnum.UI_EVENT_WECHAT_PAY_SUCCESS) {
            onRefresh();
        } else if (msg.what == EventDispatcherEnum.UI_EVENT_ALIPAY_SUCCESS) {
            onRefresh();
        }
    }
}
